import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart' hide FormData,MultipartFile;
import '../../../api/UpLoadApi.dart';
import '../../../utils/Settings.dart';
import '../../../utils/Utils.dart';
import '../../ScreenPage.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'dart:core';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../../form/LFormLogic.dart';
import '../../get/MyController.dart' hide FormData,MultipartFile;
import 'LFormImageUpState.dart';




class LFormImageUpLogic extends MyController{

  final state = LFormImageUpState();


  void init({required Map formItem,required Map formData,String? betweenSign,required String formTag,required String formType}){
    state.formItem = formItem;
    state.formData = formData;
    state.betweenSign = betweenSign??"";
    state.fileList=[];
    state.fileVal=[];
    state.imagePicker = ImagePicker();
    state.formTag = formTag;
    state.formType = formType;

    //初始化真是图片路径
    initFileList();
  }

  void initFileList(){
    if(!Utils.isEmpty(state.formData[state.formItem['field']])){
      state.fileList = state.formData[state.formItem['field']].toString().split(",");
      state.fileVal = state.formData[state.formItem['field']].toString().split(",");
    }

    for(int i=0;i<state.fileList.length;i++){
      state.fileList[i] = '${Settings.fileServer}/${state.fileList[i]}';
    }
    update();
  }

  List<Widget> createImagesList (context){
    List<Widget> li = [];
    for(int i=0;i<state.fileList.length;i++){
      li.add(
          InkWell(
            onTap: (){
              Navigator.push(context,MaterialPageRoute(builder:(BuildContext context)=> ScreenPage(isCanDel:state.formItem["readonly"]!=true,path:'${state.fileList[i]}',deleteImageCallback:deleteImage,)));
            },
            child: CachedNetworkImage(imageUrl: '${state.fileList[i]}',width: 60,height: 60, fit: BoxFit.cover,),
          )
      );
    }
    if(state.formItem["readonly"]==true){
      return li;
    }
    if(state.formItem["maxCount"]!=null && li.length>=state.formItem["maxCount"]){
      return li;
    }

    li.add(
      Container(
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(8),border: Border.all(color:Colors.black26)),
        constraints: const BoxConstraints(maxHeight: 60,maxWidth: 60,minHeight: 60,minWidth: 60),
        child: TextFormField(
            readOnly: true,
            textAlign: TextAlign.center,
            decoration: const InputDecoration(
                hintText: "+",
                hintStyle: TextStyle(color: Colors.black26,fontSize: 28),
                enabledBorder: InputBorder.none,
                disabledBorder: InputBorder.none,
                focusedBorder: InputBorder.none,
                errorBorder: InputBorder.none
            ),
            onTap: (){
              showCustomModalBottomSheet(context);
            },
            onChanged:(v){},
            onSaved: (v){},
            validator: (v) {
              //非空验证
              if (state.formItem["required"] == true && (state.formData[state.formItem['field']]==null || state.formData[state.formItem['field']]=="")) {
                return "不能为空";
              }

            }
        ),
      ),
    );

    return li;
  }

  void deleteImage(path){
    int index = -1;
    for(int i=0;i<state.fileList.length;i++){
      if(path==state.fileList[i]){
        index = i;
        break;
      }
    }
    if(index<0){
      return;
    }
    state.fileList.removeAt(index);
    state.fileVal.removeAt(index);
    state.formData[state.formItem['field']]=state.fileVal.join(",");
    if(state.formType==Settings.formType["表单"]){
      Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':state.fileVal.join(",")});

    }
    update();
  }

  upload(image)async{

    if(state.formItem["maxCount"]!=null && state.fileList.length>=state.formItem["maxCount"]){
      EasyLoading.showError("只能上传${state.formItem["maxCount"]}个图片");
      return;
    }

    FormData formdata = FormData.fromMap({
      "file": await MultipartFile.fromFile(image.path, filename: image.name)
    });
    EasyLoading.show(status: "上传中...");
    dynamic res = await UpLoadApi.imageUp(formdata,(int count, int data){
      //可以计算进度
    });
    EasyLoading.dismiss();
    if(res["success"]){
      state.fileList.add("${Settings.fileServer}/${res['message']}");
      state.fileVal.add(res['message']);
      state.formData[state.formItem['field']]=state.fileVal.join(",");
      if(state.formType==Settings.formType["表单"]){
        Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':state.fileVal.join(",")});
      }
      update();
    }else{
      EasyLoading.showToast(res["message"]);
    }
  }


  Future<dynamic> showCustomModalBottomSheet(context) async {
    return showModalBottomSheet<dynamic>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return Container(
          clipBehavior: Clip.antiAlias,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.0),
              topRight: Radius.circular(20.0),
            ),
          ),
          height: MediaQuery.of(context).size.height / 3.0,
          child: Column(children: [
            SizedBox(
              height: 50,
              child: Stack(
                textDirection: TextDirection.rtl,
                children: [

                  const Center(
                    child: Text('选择操作',style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0),),
                  ),
                  IconButton(
                      icon: const Icon(Icons.close),
                      onPressed: () {
                        Navigator.of(context).pop();
                      }),
                ],
              ),
            ),
            const Divider(height: 1.0),
            Expanded(
              child: GridView(
                  padding: const EdgeInsets.only(top: 10),
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 4, //横轴三个子widget
                      childAspectRatio: 1.3 //宽高比为1时，子widget
                  ),
                  children:<Widget>[
                    GestureDetector(
                        child: Column(
                          children: [
                            Image.asset("images/paizhao.png",width: 45,height: 45,),
                            const SizedBox(height: 2,),
                            const Text("相机")
                          ],
                        ),
                        onTap: () async {
                          XFile? image = await state.imagePicker.pickImage(source: ImageSource.camera);
                          if (image != null){
                            upload(image);
                          }

                          // Navigator.pop(context);
                        }

                    ),
                    GestureDetector(
                      child: Column(
                        children: [
                          Image.asset("images/xiangce.png",width: 45,height: 45,),
                          const SizedBox(height: 2,),
                          const Text("相册")
                        ],
                      ),
                      onTap:()async{
                        //选择多个文件
                        // List<XFile>? images = await _imagePicker.pickMultiImage();
                        //
                        // if(images.length>maxImageCount){
                        //
                        //   return;
                        // }

                        //选择文件时就关闭弹出页
                        // Navigator.pop(context);
                        //单个文件选择
                        XFile? image = await state.imagePicker.pickImage(source: ImageSource.gallery);
                        if (image != null){
                          upload(image);
                        }

                      } ,
                    )

                  ]
              ),
            ),
          ]),
        );
      },
    );
  }
}